package com.nforce.linremote;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.GridLayout;
import android.widget.GridLayout.LayoutParams;
import android.widget.ImageButton;
import android.widget.TextView;

import com.nforce.linremote.model.LButton;
import com.nforce.linremote.model.LButtonArg;
import com.nforce.linremote.model.Program;
import com.nforce.linremote.model.Script;
import com.nforce.linremote.scripting.FileHelper;
import com.nforce.linremote.serverapi.Library;

public class ProgramDetailFragment extends Fragment {

    public static final String ARG_ITEM_ID = "item_id";

    private Program mItem;

    private GridLayout mGridLayout;

    public ProgramDetailFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	AsyncTask<Void, Void, Void> loadJob = new AsyncTask<Void, Void, Void>() {

	    @Override
	    protected Void doInBackground(Void... params) {
		mItem = new Program(getArguments(), true);
		return null;
	    }
	};
	try {
	    loadJob.execute().get();
	} catch (InterruptedException e) {
	    e.printStackTrace();
	} catch (ExecutionException e) {
	    e.printStackTrace();
	}
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	View rootView = inflater.inflate(R.layout.fragment_program_detail, container, false);

	if (mItem != null) {
	    ((TextView) rootView.findViewById(R.id.program_detail)).setText(mItem.getName());
	    mGridLayout = (GridLayout) rootView.findViewById(R.id.program_grid);
	    mGridLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

		@Override
		public void onGlobalLayout() {
		    if (mGridLayout.getWidth() > 0) {
			int gridWidth = mGridLayout.getWidth();
			Resources r = getResources();
			int columnCount = mGridLayout.getColumnCount();
			int margins = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics()) * columnCount;
			for (int i = 0; i < mGridLayout.getChildCount(); i++) {
			    View child = mGridLayout.getChildAt(i);
			    int calculatedSize = (gridWidth - margins) / columnCount;
			    child.setMinimumWidth(calculatedSize);
			    child.setMinimumHeight(calculatedSize);
			}
		    }
		}
	    });

	    if (mItem.getScript() == null) {
		return rootView;
	    }

	    Resources r = getResources();
	    int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, r.getDisplayMetrics());

	    for (final LButton b : mItem.getScript().getButtons()) {

		ImageButton button = (ImageButton) inflater.inflate(R.layout.button, mGridLayout, false);

		Bitmap bm = BitmapFactory.decodeStream(FileHelper.getFileForReading(b.getImage()));
		button.setImageBitmap(bm);
		button.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			sendCommand(b.getCommand(), b.getArgs(), mItem.getScript());
		    }
		});
		LayoutParams params = new LayoutParams();
		params.rowSpec = GridLayout.spec(b.getRow());
		params.columnSpec = GridLayout.spec(b.getColumn());
		params.setMargins(margin, margin, margin, margin);
		mGridLayout.addView(button, params);
	    }
	}

	return rootView;
    }

    private void sendCommand(final String command, final List<LButtonArg> args, final Script script) {
	AsyncTask<Void, Void, Boolean> sendJob = new AsyncTask<Void, Void, Boolean>() {

	    @Override
	    protected Boolean doInBackground(Void... params) {
		List<Object> oArgs = new ArrayList<Object>();
		for (LButtonArg a : args) {
		    if (a.isEditable()) {
			try {
			    a.setArg(BlockingDialog.askArg(getActivity(), a.getTitle(), (String) a.getArg()));
			} catch (InterruptedException e) {
			}
		    }
		    oArgs.add(a.getArg());
		}
		Library.execute(command, oArgs, script);
		return true;
	    }
	};
	sendJob.execute((Void) null);
    }
}
